<template>
  <el-dialog
    v-model="visibility"
    :title="props.rowData.id ? config.button.text.edit : config.button.text.add"
    width="60%"
    append-to-body
    draggable
    :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="config.form.label.width"
      status-icon>
      <el-row>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="资金仓库"
            prop="baseCapitalWarehouseId">
            <el-select
              v-model="formData.baseCapitalWarehouseId"
              placeholder="请选择资金仓库"
              style="width: 100%"
              filterable
              clearable>
              <el-option
                v-for="item in warehouseSimpleNameList"
                :key="item.id"
                :disabled="item.disabled"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="商品名称"
            prop="baseRiceBarnGoodsId">
            <el-input
              v-model="formData.goodsName"
              clearable
              placeholder="商品名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="司机名称"
            prop="driverName">
            <el-input
              v-model="formData.driverName"
              clearable
              placeholder="司机名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="司机电话"
            prop="driverPhoneNumber">
            <el-input
              v-model="formData.driverPhoneNumber"
              clearable
              placeholder="司机电话"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="司机身份证"
            prop="driverIdCard">
            <el-input
              v-model="formData.driverIdCard"
              clearable
              placeholder="司机身份证"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="车牌号"
            prop="carNumber">
            <el-input
              v-model="formData.carNumber"
              clearable
              placeholder="车牌号"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="购买吨数"
            prop="buyTon">
            <el-input-number
              v-model="formData.buyTon"
              style="width: 100%;"
              clearable
              :min="0"
              placeholder="购买吨数"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="购买袋数"
            prop="buyBagCount">
            <el-input-number
              v-model="formData.buyBagCount"
              style="width: 100%;"
              :min="0"
              clearable
              placeholder="购买袋数"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="是否完成提货"
            prop="isFinishPick">
            <el-select
              v-model="formData.isFinishPick"
              placeholder="选择"
              clearable>
              <el-option
                :label="config.button.text.yes"
                :value="true" />
              <el-option
                :label="config.button.text.no"
                :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="启用状态"
            prop="isEnable">
            <el-select
              v-model="formData.isEnable"
              placeholder="选择"
              clearable>
              <el-option
                :label="config.button.text.enable"
                :value="true" />
              <el-option
                :label="config.button.text.stop"
                :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="备注"
            prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="备注"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="图片"
            prop="fileDataJson">
            <UploadFile
              ref="uploadRef"
              :show="true"
              :file-uuids="fileDataList"
              @success="success"
              @delete-file="deleteFile" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col
          :span="24"
          class="el_col_fit">
          <el-form-item
            label="自动识别">
            <el-input
              v-model="formData.recognition"
              type="textarea"
              @blur="getInfo"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请按照（姓名/手机号/身份证/车牌号/仓库名称/商品名称/购买吨数/购买袋数/备注）格式来识别信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
        <el-button
          type="primary"
          @click="saveEvent">
          {{ config.button.text.save }}
        </el-button>
      </div>
    </template>
    <el-dialog
      title="预览"
      v-model="dialogVisible">
      <img
        w-full
        :src="dialogImageUrl"
        alt="Preview Image" />
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import config from "@/common/element-plus/config";
import ApiLogisticsRecord from "@/api/modules/logistics-record"
import { useValidator } from "@/hooks/useValidator";
import ApiBaseRiceBarn from "@/api/modules/base-rice-barn";
import message from "@/common/element-plus/message";
import UploadFile from "@/components/UploadFile.vue"

const visibility = ref(false)
const formData = ref({})
const formRef = ref()
const { required, validate, clearValidate } = useValidator()

const formRules = {
  baseCapitalWarehouseId: [required("资金仓库名称")],
  goodsName: [required("商品名称")],
  buyTon: [required("购买吨数")],
  driverName: [required("司机名字")],
  driverPhoneNumber: [required("司机电话")],
  carNumber: [required("车牌号")],
  driverIdCard: [required("司机身份证号")],
  isFinishPick: [required("启用状态", "change")],
  buyBagCount: [required("购买袋数")],
  isEnable: [required("启用状态", "change")],
}

const props = defineProps(["rowData"])

const warehouseSimpleNameList = ref([])
const goodsSimpleNameList = ref([]);

const token = localStorage.getItem(localStorage.getItem("tokenName"))
const headers = ref({});
if (token) {
  headers.value["yg-token"] = token;
}
const fileDataList = ref();
const imageList = ref([]);
const dialogImageUrl = ref();
const dialogVisible = ref(false);


//获取资金仓库简称列表
const getWarehouseSimpleNameList = async () => {
  const orgObj = {
    id:formData.value.baseCapitalWarehouseId,
    simple_name:formData.value.baseCapitalWarehouseName,
    disabled:true
  }
  const data = await ApiLogisticsRecord.getSimpleNameList("/baseCapitalWarehouse/")
  warehouseSimpleNameList.value = data.data
  const findItem = data.data.find(item=>item.id===orgObj.id);
  if(!findItem&&props.rowData.id){
    orgObj.simple_name+='(已禁用)'
    warehouseSimpleNameList.value.push(orgObj);
  }
}

//获取商品简称列表
const getGoodsSimpleNameList = async () => {
  const data = await ApiLogisticsRecord.getSimpleNameList("/baseRiceBarnGoods/")
  goodsSimpleNameList.value = data.data
}

// 上传文件成功回调
const success = (data) => {
  const file = formData.value.fileDataJson ? JSON.parse(formData.value.fileDataJson) : []
  file.push(data)
  formData.value.fileDataJson = JSON.stringify(file)
}

// 删除文件回调
const deleteFile = (data) => {
  const file = JSON.parse(formData.value.fileDataJson)
  formData.value.fileDataJson = JSON.stringify(file.filter(item => item === data))
}

//自动识别信息
const getInfo = async() => {
  debugger
  if (formData?.value?.recognition){
    const info = encodeURI(formData?.value?.recognition);
    const res = await ApiLogisticsRecord.autoIdentifyLogisticsInfo(info);
    formData.value.driverName = res.data.name;
    formData.value.driverPhoneNumber = res.data.phone;
    formData.value.driverIdCard = res.data.idCard;
    formData.value.carNumber = res.data.carNumber;
    formData.value.baseCapitalWarehouseId = res.data.baseCapitalWarehouseId;
    formData.value.goodsName = res.data.goodsName;
    formData.value.buyTon = res.data.count;
    formData.value.buyBagCount = res.data.bagCount;
    formData.value.remark = res.data.remark;
  }
}

const emits = defineEmits(["save"])

watch(() => visibility.value, (newVal) => {
  if (newVal) {
    formData.value = props.rowData;
    getWarehouseSimpleNameList();
    getGoodsSimpleNameList();
    imageList.value = [];
    fileDataList.value = []
    if (formData.value.fileDataJson&&Array.isArray(JSON.parse(formData.value.fileDataJson))){
      fileDataList.value = JSON.parse(formData.value.fileDataJson);
      if (fileDataList.value.length>0){
        getImageList();
      }
    } else {
      imageList.value = []
    }
    // 新增（rowData.id 不存在）
    if (!props.rowData.id) {
      formData.value = {
        ...props.rowData,
        isEnable: true,
        isFinishPick: false
      };
    } else {
      //编辑
      formData.value = { ...props.rowData };
    }
    setTimeout(() => {
      clearValidate(formRef.value);
    });
  }
}, { immediate: true });

const saveEvent = async () => {
  await validate(formRef.value)
  formData.value.fileDataJson = JSON.stringify(fileDataList.value)
  if (formData.value.id) {
    await ApiLogisticsRecord.update(formData.value)
  } else {
    await ApiLogisticsRecord.insert(formData.value)
  }
  emits("save")
}

//获取图片列表
const getImageList = async () => {
  let res = await ApiBaseRiceBarn.getPicture(fileDataList.value);
  imageList.value = res.data;
}

defineExpose({ visibility })
</script>

<style lang="scss" scoped>
  .el-row {
    align-items: flex-start;
  }
  .imageList{
    color: #409eff;
    li{
      display: flex;
      align-items: center;
      .el-icon{
        margin-right: 5px;
      }
    }
    li:hover{
      cursor: pointer;
    }
  }
  @media screen and (max-width: 700px) {
    :deep(.el-form-item__label) {
      width: 100px !important;
    }
  }
</style>
